package com.mlm.mlmapp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.tablayout.view.CollectionDresserCardFragment;
import com.flyco.tablayout.view.CollectionStyleCardFragment;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.TipsView;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;
import com.mlm.mlmapp.utils.StringEncrypt;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.userinfo)
public class UserInfoActivity extends BaseActivity {

	AQuery aq;

	@Pref
	Prefs_ pref;
	@StringRes
	String msg_error;
	@ViewById
	ImageView iv_headimg;
	@ViewById
	TextView tv_coupon;
	@ViewById
	Button btn_coupon;
	@ViewById
	Button btn_sign;
	@ViewById
	TextView tv_points;
	@ViewById
	Button btn_points;
	@ViewById
	Button btn_about_us;
	@ViewById
	Button btn_ads;
	@ViewById
	TextView tv_collections;
	@ViewById
	Button btn_collections;
	@ViewById
	TextView tv_username;
	@ViewById
	TipsView btn_unpay;
	String proxyInfoId;
	ActionSheetDialog dialog;
	@StringRes
	String take_photo;
	@StringRes
	String from_photos;
	@ColorRes
	int red;
	@ColorRes
	int blacktext;
	public static final String IMAGE_FILE_NAME = "avatar.jpg";
	AjaxCallback<JSONObject> uploadHeadimg;
	private Bitmap photo;
	@Click
	void btn_points() {
		PointListActivity_.intent(this).start();
	}

	@Click
	void btn_buy() {
		BuyPointListActivity_.intent(this).start();
	}

	@OnActivityResult(REQUEST_CODE)
	void onResult(int resultcode, Intent data) {
		if (resultcode == RESULT_CANCELED) {
			return;
		}
		if (data != null) {
			if (data.getBooleanExtra("flag", false)) {
				update();
			} else {
				this.finish();
			}
		}
	}

	@OnActivityResult(AN_REQUEST_CODE)
	void onResultAN(Intent data) {
		update();
	}

	@AfterViews
	void init() {
		btn_userinfo.setCompoundDrawablesWithIntrinsicBounds(null,
				getResources().getDrawable(R.drawable.mychecked), null, null);
		btn_userinfo.setTextColor(getResources().getColor(R.color.red));
		String title = getTitle().toString();
		if (!"".equals(title)) {
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}

		setTranStatusBar();
		aq = new AQuery(this);
		if ("0".equals(pref.loginID().get())) {
			// LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			update();
		}
		uploadHeadimg = new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject html, AjaxStatus status) {
				if(status.getCode()==-101){
					Toast.makeText(UserInfoActivity.this,"网络异常,请检查网络", Toast.LENGTH_SHORT);
					return;
				}
				if (status.getCode() != 200) {
					Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
							Toast.LENGTH_LONG).show();
				} else {
					try {
						if (html.getBoolean("isSuccess")) {
							Toast.makeText(aq.getContext(), "上传成功",
									Toast.LENGTH_LONG).show();
							iv_headimg.setImageBitmap(photo);
						} else {
							Toast.makeText(aq.getContext(),
									html.getString("errors"), Toast.LENGTH_LONG)
									.show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		};


	}
	@Click
	void btn_coupon(){
		CouponMineActivity_.intent(this).start();
	}
	private void getUnpayedOrder() {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
		pairs.add(new BasicNameValuePair("page", 1 + ""));
		pairs.add(new BasicNameValuePair("status", OrdersActivity.TYPE_NONPAY
				+ ""));
		CommonUtils.postRequest4Array(get_orders, aq,
				new AjaxCallback<JSONArray>() {

					@Override
					public void callback(String url, JSONArray array,
										 AjaxStatus status) {

						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						// TODO Auto-generated method stub
						if (status.getCode() == 200) {
							if (array != null && array.length() > 0) {
								btn_unpay.setVisibility(View.INVISIBLE);
							} else {
								btn_unpay.setVisibility(View.VISIBLE);
							}
						} else if (status.getCode() == 500) {
							// Toast.makeText(aq.getContext(),
							// "服务器异常:" + status.getCode() + "启用测试数据",
							// Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(aq.getContext(),
									"网络异常:" + status.getCode(),
									Toast.LENGTH_LONG).show();
						}
					}

				}, pairs);
	}

	private void update() {
		getUnpayedOrder();
		AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
			@Override
			public void callback(String url, JSONObject html, AjaxStatus status) {
				if (status.getCode() == -101) {
					Toast.makeText(aq.getContext(), "网络异常,请检查网络",
							Toast.LENGTH_SHORT);
					return;
				}
				if (status.getCode() == -103) {
					Toast.makeText(aq.getContext(), msg_error,
							Toast.LENGTH_LONG).show();
					return;
				}
				if (status.getCode() != 200) {
					Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
							Toast.LENGTH_LONG).show();
				} else {

					// MainActivity_.intent(LoginActivity.this).start();
					// userName iconPhotoUrl mobile balance integral
					// collecNum couponNum

					tv_username.setText(CommonUtils.getJsonString(html,
							"userName"));
					tv_points.setText(CommonUtils.getJsonString(html,
							"integral"));
					tv_collections.setText(CommonUtils.getJsonString(html,
							"collecNum"));
					tv_coupon.setText(CommonUtils.getJsonString(html,
							"couponNum"));
					proxyInfoId=CommonUtils.getJsonString(html,
							"proxyInfoId");
					if ("".equals(CommonUtils.getJsonString(html,
							"iconPhotoUrl"))) {
						iv_headimg.setImageResource(R.drawable.headdef);
					} else {
						aq.id(iv_headimg)
								.image(CommonUtils.getJsonString(html,
										"iconPhotoUrl"),
										true,
										true,
										200,
										0,
										BitmapFactory.decodeResource(
												UserInfoActivity.this
														.getResources(),
												R.drawable.headdef),
										Constants.FADE_IN);
					}

				}
			}
		};
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
		// pairs.add(new BasicNameValuePair("mobile", "18245189375"));

		CommonUtils.postRequest(get_user_info_action, aq, cb, pairs);
	}

	@Click
	void btn_account(View v) {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			UserSettingActivity_.intent(this).startForResult(AN_REQUEST_CODE);
		}

	}

	@Click
	void btn_comments() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			MyCommentsListActivity_.intent(this).start();
		}

	}

	@Click
	void btn_studio_address() {
		StudioListActivity_.intent(this).start();
	}
	@Click
	void btn_about_us() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			Intent intent=new Intent();
			intent.putExtra("url", "http://share.mlmsalon.com/Home/Index/about");
			intent.putExtra("title","关于我们");
			intent.setClass(this, ShowWebView_.class);
			startActivity(intent);
		}


	}


	@Click
	void btn_ads() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			String key = StringEncrypt.Encrypt("mobile="+pref.loginID().get()+"&key=3e9bb86c6980c3b79e5b936ce10b9b96", "SHA-256");
			Intent intent=new Intent();
			intent.putExtra("title","合伙人");
			intent.putExtra("url", "http://share.mlmsalon.com/Home/Partner/index/mobile/"+pref.loginID().get()+"/sign/"+key);
			intent.putExtra("proxyInfoId",proxyInfoId );
			intent.setClass(this, ShowWebView_.class);
			startActivity(intent);
		}


	}
	@Click
	void btn_sign() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			String key = StringEncrypt.Encrypt("mobile="+pref.loginID().get()+"&key=3e9bb86c6980c3b79e5b936ce10b9b96", "SHA-256");
			Intent intent=new Intent();
			intent.putExtra("url", "http://share.mlmsalon.com/Home/Activity/sign/mobile/"+pref.loginID().get()+"/sign/"+key);
			intent.putExtra("title","签到有奖");
			intent.setClass(this, ShowWebView_.class);
			startActivity(intent);
		}


	}
	@Click
	void btn_order_all() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			OrdersActivity_.intent(this).extra("flag", OrdersActivity.TYPE_ALL)
					.start();
		}

	}

	@Click
	void btn_unpay() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			OrdersActivity_.intent(this)
					.extra("flag", OrdersActivity.TYPE_NONPAY).start();
		}

	}

	@Click
	void btn_appointment_success() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			OrdersActivity_.intent(this)
					.extra("flag", OrdersActivity.TYPE_BOOKED).start();
		}

	}

	@Click
	void btn_finished() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			OrdersActivity_.intent(this)
					.extra("flag", OrdersActivity.TYPE_FINISH).start();
		}

	}

	@Click
	void btn_payback() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			OrdersActivity_.intent(this)
					.extra("flag", OrdersActivity.TYPE_REFUND).start();
		}

	}

	@Click
	void iv_headimg() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		}else{
			dialog = new ActionSheetDialog(this, new String[] { take_photo,
					from_photos }, null);
			dialog.titleTextColor(red).itemTextColor(blacktext).cornerRadius(0)
					.show();
			dialog.setOnOperItemClickL(new OnOperItemClickL() {
				@Override
				public void onOperItemClick(AdapterView<?> parent, View view,
											int position, long id) {
					switch (position) {
						case 0:
							Intent intentFromCapture = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							// 判断存储卡是否可以用，可用进行存储
							intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
									.fromFile(new File(Environment
											.getExternalStorageDirectory(),
											IMAGE_FILE_NAME)));
							startActivityForResult(intentFromCapture,
									AVATAR_REQUEST_CODE);

							break;
						case 1:
							Intent intentFromGallery = new Intent();
							intentFromGallery.setType("image/*"); // 设置文件类型
							intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(intentFromGallery,
									GALLERY_AVATAR_REQUEST_CODE);
							break;
					}
					dialog.dismiss();
				}
			});
		}
	}
	@OnActivityResult(GALLERY_AVATAR_REQUEST_CODE)
	void onResultGallery(int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		if (data != null) {
			Intent intent = CommonUtils.startPhotoZoom(data.getData());
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		}
	}

	@OnActivityResult(AVATAR_REQUEST_CODE)
	void onResultTakeAvatar(int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		File tempFile = new File(Environment.getExternalStorageDirectory(),
				IMAGE_FILE_NAME);
		Intent intent = CommonUtils.startPhotoZoom(Uri.fromFile(tempFile));
		startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
	}

	@OnActivityResult(PHOTO_PICKED_WITH_DATA)
	void onResultGetAvatar(int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		if (data != null) {
			setImageToView(data);
		}
	}
	/**
	 * login request
	 *
	 * @throws UnsupportedEncodingException
	 */
	private void uploadAction(String avatar) {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
		pairs.add(new BasicNameValuePair("avatar", avatar));
		// img
		CommonUtils.postRequest(upload_avatar_action, aq, uploadHeadimg, pairs);

	}
	@Receiver(actions = CollectionsActivity.COLLECTION_REFRESH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
	protected void onOrderRefresh(Intent intent) {
		if (intent.getStringExtra("refreshflag")!=null&&"0".equals(intent.getStringExtra("refreshflag"))){
			update();

		}


	}
	private void setImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			photo = extras.getParcelable("data");
			String temp = "";
			try {
				temp = CommonUtils.encodeBase64File(CommonUtils
						.saveBitmap(photo));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			uploadAction(temp);
		}
	}
	@Click
	void ll_collection() {
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
		} else {
			// update();
			CollectionsActivity_.intent(this).start();
		}

	}

	@Click
	void btn_home() {
		MainActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
	}

	@Click
	void btn_dresser() {
		HairDresserListActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
	}

	@Click
	void btn_appointment() {
		BookActivity_.intent(this).start();
	}

	@Click
	void btn_style() {
		HairStyleListActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
	}

	@ViewById
	Button btn_userinfo;

	@Click
	void btn_userinfo() {
		// UserInfoActivity_.intent(this).start();

	}

}
